/*******************************************************************************************
 * Copyright (c) 2009 Alex Robson, Rob Simmons, Craig Israel, and Rachel Twyford
 *
 * Use of this software in any form requires that you have both 
 * read and agreed to the following terms:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions: 
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the 
 * documentation and/or other materials provided with the distribution.
 * Neither the name of Nvigorate nor the names of its contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using Nvigorate.Xml;

namespace Nvigorate.Data.Query
{
    public enum JoinType
    {
        None,
        Inner,
        Left,
        Right,
        FullOuter
    }

    [Serializable]
    public class Table : QueryObject<Table>
    {
        protected Queue<Table> _joinedTables = new Queue<Table>();
        protected SearchCriteria _joinCriteria = new SearchCriteria();
        protected bool _isVariable = false;
        protected JoinType _joinType = JoinType.None;

        public Queue<Table> JoinedTables
        {
            get { return _joinedTables; }
        }

        public SearchCriteria JoinCriteria
        {
            get { return _joinCriteria; }
        }

        public JoinType JoinType
        {
            get { return _joinType; }
            set { _joinType = value; }
        }

        public bool IsVariable
        {
            get { return _isVariable; }
            set { _isVariable = value; }
        }

        #region Overrides of QueryComponent

        public override XElement GetXElementRepresentation()
        {
            XElement criteria = _joinCriteria.GetXElementRepresentation();
            if(criteria != null)
                criteria.Name = "on";

            return new XElement("table",
                    new XAttribute("name", _name),
                    new XAttribute("alias", _alias),
                    new XAttribute("owner", _owner),
                    new XAttribute("variable", _isVariable),
                    criteria,
                    new XElement("joins", _joinedTables.Select(j => j.GetXElementRepresentation()))
                );
        }

        public override object ParseXElement(XElement element)
        {
            var criteriaElement = element.Element("on");
            var joins = element.Element("joins");

            _name = element.GetAttributeValue("name") ?? "";
            _alias = element.GetAttributeValue("alias") ?? "";
            _owner = element.GetAttributeValue("owner") ?? "";
            _isVariable = bool.Parse(element.GetAttributeValue("variable") ?? "false");
            _joinCriteria = criteriaElement != null ?
                (SearchCriteria) new SearchCriteria().ParseXElement(criteriaElement) 
                : new SearchCriteria();
            if(joins != null)
            {
                joins
                    .Descendants()
                    .ToList()
                    .ForEach(j => _joinedTables.Enqueue((Table) new Table().ParseXElement(j)));
            }

            return this;
        }

        #endregion

        public static Table From(string table)
        {
            return new Table(table);
        }

        public static Table Variable(string table)
        {
            return new Table(table) {IsVariable = true};
        }

        public Table Join(params Table[] tables)
        {
            if(tables == null)
                return this;

            tables
                .ToList()
                .ForEach(t =>
                             {
                                 Debug.Assert(t._joinCriteria.Count != 0);
                                 _joinedTables.Enqueue(t);
                             });
            return this;
        }

        public static Table InnerJoin(string table)
        {
            return new Table(table) {_joinType = Query.JoinType.Inner};
        }

        public static Table LeftJoin(string table)
        {
            return new Table(table) { _joinType = Query.JoinType.Left };
        }

        public static Table RightJoin(string table)
        {
            return new Table(table) { _joinType = Query.JoinType.Right };
        }

        public static Table FullOuterJoin(string table)
        {
            return new Table(table) { _joinType = Query.JoinType.FullOuter };
        }

        public Table On(SearchCriteria joinCriteria)
        {
            _joinCriteria = joinCriteria;
            return this;
        }

        public Table JoinInstruction(JoinType joinType)
        {
            _joinType = joinType;
            return this;
        }

        internal Table(string name)
            : base(name)
        {
        }

        internal Table()
        {}
    }
}